package com.itlaobing.filter;

import java.io.IOException;
import javax.servlet.*;

/**
 * 字符编码过滤器
 * @author Ma_Hao
 *
 */
public class CharacterEncodingFilter implements Filter{

    protected String encoding = null;
    protected FilterConfig filterConfig = null;

    /**
     * 初始化过滤器
     * 获取初始化字符编码
     */
    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
        this.encoding = filterConfig.getInitParameter("encoding");
    }

    /**
     * 设置字符编码
     */
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        if (encoding != null) {
            request.setCharacterEncoding(encoding);
            response.setContentType("text/html; charset="+encoding);
        }
        chain.doFilter(request, response);
    }
    
    /**
     * 销毁
     */
    public void destroy() {
        this.encoding = null;
        this.filterConfig = null;
    }
}
